package com.eduplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eduplatform.common.Result;
import com.eduplatform.dto.SubjectDTO;
import com.eduplatform.dto.TeacherDTO;
import com.eduplatform.entity.School;
import com.eduplatform.entity.Subject;
import com.eduplatform.entity.User;
import com.eduplatform.service.SchoolService;
import com.eduplatform.service.SubjectService;
import com.eduplatform.service.TeacherSubjectService;
import com.eduplatform.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/teachers")
@CrossOrigin
public class TeacherController {

    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private TeacherSubjectService teacherSubjectService;

    /**
     * 分页获取教师列表
     */
    @GetMapping("/list")
    public Result<Page<TeacherDTO>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "educationLevel", required = false) Integer educationLevel) {

        // 创建分页对象
        Page<User> pageInfo = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole, 1); // 查询教师角色
        queryWrapper.eq(User::getIsDeleted, 0); // 未删除

        // 按教育阶段筛选
        if (educationLevel != null) {
            queryWrapper.eq(User::getEducationLevel, educationLevel);
        }

        // 关键字搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getNickname, keyword)
                    .or()
                    .like(User::getPhone, keyword)
                    .or()
                    .like(User::getEmail, keyword));
        }

        // 排序
        queryWrapper.orderByDesc(User::getCreateTime);

        // 查询
        userService.page(pageInfo, queryWrapper);

        // 转换为DTO
        List<TeacherDTO> teacherDTOList = new ArrayList<>();
        for (User user : pageInfo.getRecords()) {
            TeacherDTO teacherDTO = new TeacherDTO();
            BeanUtils.copyProperties(user, teacherDTO);

            // 设置学校名称
            if (user.getSchoolId() != null) {
                School school = schoolService.getById(user.getSchoolId());
                if (school != null) {
                    teacherDTO.setSchoolName(school.getName());
                }
            }

            // 获取教师任教的学科
            List<Long> subjectIds = teacherSubjectService.getSubjectIdsByTeacherId(user.getId());
            teacherDTO.setSubjectIds(subjectIds);

            if (!subjectIds.isEmpty()) {
                List<Subject> subjects = subjectService.listByIds(subjectIds);
                List<SubjectDTO> subjectDTOs = subjects.stream().map(subject -> {
                    SubjectDTO subjectDTO = new SubjectDTO();
                    BeanUtils.copyProperties(subject, subjectDTO);
                    return subjectDTO;
                }).collect(Collectors.toList());
                teacherDTO.setSubjects(subjectDTOs);
            }

            // 清除密码
            teacherDTO.setPassword(null);

            teacherDTOList.add(teacherDTO);
        }

        // 创建返回结果
        Page<TeacherDTO> teacherDTOPage = new Page<>();
        teacherDTOPage.setRecords(teacherDTOList);
        teacherDTOPage.setTotal(pageInfo.getTotal());
        teacherDTOPage.setCurrent(pageInfo.getCurrent());
        teacherDTOPage.setSize(pageInfo.getSize());

        return Result.success(teacherDTOPage);
    }

    /**
     * 添加教师
     */
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody @Valid TeacherDTO teacherDTO) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, teacherDTO.getUsername());
        if (userService.count(queryWrapper) > 0) {
            return Result.error("用户名已存在");
        }

        // 检查学校是否存在
        School school = schoolService.getById(teacherDTO.getSchoolId());
        if (school == null) {
            return Result.error("所选学校不存在");
        }

        // 创建教师用户
        User user = new User();
        BeanUtils.copyProperties(teacherDTO, user);

        // 设置教师角色
        user.setRole(1);

        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        // 设置默认头像
        if (user.getAvatar() == null || user.getAvatar().isEmpty()) {
            user.setAvatar("https://via.placeholder.com/150");
        }

        // 设置创建时间和更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        // 设置未删除
        user.setIsDeleted(0);

        // 保存
        boolean result = userService.save(user);

        // 保存教师与学科的关联
        if (result && teacherDTO.getSubjectIds() != null && !teacherDTO.getSubjectIds().isEmpty()) {
            teacherSubjectService.saveTeacherSubjects(user.getId(), teacherDTO.getSubjectIds());
        }

        return Result.success(result);
    }

    /**
     * 更新教师信息
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody @Valid TeacherDTO teacherDTO) {
        // 检查教师是否存在
        User existingUser = userService.getById(teacherDTO.getId());
        if (existingUser == null || existingUser.getRole() != 1) {
            return Result.error("教师不存在");
        }

        // 检查学校是否存在
        School school = schoolService.getById(teacherDTO.getSchoolId());
        if (school == null) {
            return Result.error("所选学校不存在");
        }

        // 更新教师信息
        User user = new User();
        BeanUtils.copyProperties(teacherDTO, user);

        // 保持角色不变
        user.setRole(1);

        // 如果密码为空，保持原密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(existingUser.getPassword());
        } else {
            // 密码加密
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }

        // 设置更新时间
        user.setUpdateTime(new Date());

        // 更新
        boolean result = userService.updateById(user);

        // 更新教师与学科的关联
        if (result && teacherDTO.getSubjectIds() != null) {
            teacherSubjectService.saveTeacherSubjects(user.getId(), teacherDTO.getSubjectIds());
        }

        return Result.success(result);
    }

    /**
     * 删除教师
     */
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        // 检查教师是否存在
        User existingUser = userService.getById(id);
        if (existingUser == null || existingUser.getRole() != 1) {
            return Result.error("教师不存在");
        }

        // 删除教师与学科的关联
        teacherSubjectService.saveTeacherSubjects(id, new ArrayList<>());

        // 逻辑删除
        boolean result = userService.removeById(id);

        return Result.success(result);
    }

    /**
     * 获取教师详情
     */
    @GetMapping("/detail/{id}")
    public Result<TeacherDTO> detail(@PathVariable Long id) {
        // 获取教师信息
        User user = userService.getById(id);
        if (user == null || user.getRole() != 1) {
            return Result.error("教师不存在");
        }

        // 转换为DTO
        TeacherDTO teacherDTO = new TeacherDTO();
        BeanUtils.copyProperties(user, teacherDTO);

        // 设置学校名称
        if (user.getSchoolId() != null) {
            School school = schoolService.getById(user.getSchoolId());
            if (school != null) {
                teacherDTO.setSchoolName(school.getName());
            }
        }

        // 获取教师任教的学科
        List<Long> subjectIds = teacherSubjectService.getSubjectIdsByTeacherId(id);
        teacherDTO.setSubjectIds(subjectIds);

        if (!subjectIds.isEmpty()) {
            List<Subject> subjects = subjectService.listByIds(subjectIds);
            List<SubjectDTO> subjectDTOs = subjects.stream().map(subject -> {
                SubjectDTO subjectDTO = new SubjectDTO();
                BeanUtils.copyProperties(subject, subjectDTO);
                return subjectDTO;
            }).collect(Collectors.toList());
            teacherDTO.setSubjects(subjectDTOs);
        }

        // 清除密码
        teacherDTO.setPassword(null);

        return Result.success(teacherDTO);
    }
}